from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from . import models
from .serializer import *
from django.core.paginator import Paginator

# 商品
class GoodsView(APIView):
    # 查询
    def get(self, request):
        # 1 接收前端的参数
        p = int(request.GET.get("p", 1))

        # 2 查询所有的商品数据
        goodsobj = models.Goods.objects.all()

        # 3 实例化分页
        page_obj = Paginator(goodsobj, per_page=2)

        # 4 获取分页的范围
        page = [i for i in page_obj.page_range]

        # 5 获取当前页的数据
        page_data = page_obj.page(p)

        # 6 判断上一页和下一页
        previous = page_data.has_previous()
        next = page_data.has_next()

        # 7 序列化当前页数据
        obj = GoodsSerializer(page_data, many=True)

        # 8 构造数据
        data = {
            "data": obj.data,
            "page": page,
            "previous": previous,
            "next": next
        }

        # 9 返回值
        return Response({"code": 1000, "msg": "", "data": data})

    # 添加
    def post(self,request):
        name=request.POST.get('name','').strip()
        price=request.POST.get('price','')
        img=request.FILES.get('img')
        count=request.POST.get('count',0)

        data={
            'name':name,
            'price':price,
            'img':img,
            'count':count
        }

        obj=GoodsUnserializer(data=data)

        if obj.is_valid():
            flag=obj.save()
            if flag:
                return Response({'code':1000,'msg':'添加成功'})
            return Response({'code': 1001, 'msg': '添加失败'})

        print(obj.errors)
        return Response({'code': 1002, 'msg': '参数有误'})


class AllgoodsView(APIView):

    def get(self,request):
        goodsquery=models.Goods.objects.all()
        obj=GoodsSerializer(goodsquery,many=True)
        return Response({'code':1000,'msg':'','data':obj.data})


